package pers.cz.jefconfig.tools;

import pers.cz.jefconfig.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.zip.CRC32;

/**
 * @program: JefConfig
 * @description: 工具类
 * @author: Cheng Zhi
 * @create: 2022-07-14 09:43
 **/
public class StringUtils {

    /**
     * 字符串分割
     * @param strings
     * @param symbol
     * @return
     */
    public static String[] split(String strings, String symbol) {
        String[] split = strings.split(symbol);
        return split;
    }

    /**
     * 将String转换为Boolean,如果转换不成功，则返回默认类型
     * @param s
     * @param defaultValue
     * @return
     */
    public static Boolean toBoolean(String s, Boolean defaultValue) {

        if ("TRUE".equalsIgnoreCase(s) || "1".equals(s) || "Y".equalsIgnoreCase(s) || "ON".equalsIgnoreCase(s)) {
            return true;
        }

        if ("FALSE".equalsIgnoreCase(s) || "0".equalsIgnoreCase(s) || "N".equalsIgnoreCase(s) || "OFF".equalsIgnoreCase(s)) {
            return false;
        }

        if (defaultValue == null) {
            // 如果不指定默认值，且没有符合上述判断条件的，那么认为这个s不适合转换为Boolean,因此要抛出异常。
            throw new IllegalArgumentException(s + " can not be case to boolean.");
        }

        return defaultValue;
    }

    /**
     * 字符替换
     * @param str
     * @param searchChars
     * @param replaceChars
     * @return
     */
    public static String replaceChars(String str, String searchChars, String replaceChars) {
        if (!isEmpty(str) && !isEmpty(searchChars)) {
            if (replaceChars == null) {
                replaceChars = "";
            }

            boolean modified = false;
            int replaceCharsLength = replaceChars.length();
            int strLength = str.length();
            StringBuilder buf = new StringBuilder(strLength);

            for(int i = 0; i < strLength; ++i) {
                char ch = str.charAt(i);
                int index = searchChars.indexOf(ch);
                if (index >= 0) {
                    modified = true;
                    if (index < replaceCharsLength) {
                        buf.append(replaceChars.charAt(index));
                    }
                } else {
                    buf.append(ch);
                }
            }

            if (modified) {
                return buf.toString();
            } else {
                return str;
            }
        } else {
            return str;
        }
    }

    /**
     * 是否为空
     * @param cs
     * @return
     */
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * 截取指定字符串中关键字之前的内容
     * @param str
     * @param separator
     * @return
     */
    public static String substringBefore(String str, String separator) {
        if (!isEmpty(str) && separator != null) {
            if (separator.isEmpty()) {
                return "";
            } else {
                int pos = str.indexOf(separator);
                return pos == -1 ? str : str.substring(0, pos);
            }
        } else {
            return str;
        }
    }

    /**
     * 截取指定字符串中关键字之后的内容
     * @param str
     * @param separator
     * @return
     */
    public static String substringAfter(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        } else if (separator == null) {
            return "";
        } else {
            int pos = str.indexOf(separator);
            return pos == -1 ? "" : str.substring(pos + separator.length());
        }
    }

    public static String subStringLast(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        } else if (separator == null) {
            return "";
        } else {
            int pos = str.lastIndexOf(separator);
            return pos == -1 ? "" : str.substring(pos + separator.length());
        }
    }
    /**
     *
     * @param str
     * @param separator
     * @return
     */
    public static String substringAfterLast(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        } else if (isEmpty(separator)) {
            return "";
        } else {
            int pos = str.lastIndexOf(separator);
            return pos != -1 && pos != str.length() - separator.length() ? str.substring(pos + separator.length()) : "";
        }
    }

    /**
     * 计算CRC摘要,8位十六进制数
     */
    public static String getCRC(InputStream in) {
        CRC32 crc32 = new CRC32();
        byte[] b = new byte[65536];
        int len = 0;
        try {
            while ((len = in.read(b)) != -1) {
                crc32.update(b, 0, len);
            }
            return Long.toHexString(crc32.getValue());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * 计算CRC摘要,8位十六进制数
     */
    public static String getCRC(String s) {
        ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes());
        return getCRC(in);
    }

    /**
     * 将给定单词转化为驼峰命名法
     * @param word
     * @return
     */
    public static String getCamelCase(String word) {

        if (!word.contains("_")) {
            return returnFirstCaps(word);
        }

        String[] s = word.split("_");
        StringBuilder sb = new StringBuilder();
        for (String splitWord : s) {

            sb.append(returnFirstCaps(splitWord));
        }
        return sb.toString();
    }

    public static String getCamelCaseField(String word) {

        if (!word.contains("_")) {
            return word;
        }

        String[] s = word.split("_");
        StringBuilder sb = new StringBuilder();
        int cont = 0;
        for (String splitWord : s) {
            if (cont == 0) {
                sb.append(splitWord);
            } else {
                sb.append(returnFirstCaps(splitWord));
            }
            cont ++;
        }
        return sb.toString();
    }

    /**
     * 将给定单词首字母转化为大写
     * @param word
     * @return
     */
    public static String returnFirstCaps(String word) {

        if (word.length() == 0) {
            return word;
        }

        char[] chars = word.toCharArray();
        char firstLetter = chars[0];
        // 先判断是否属于字母
        if (firstLetter >= 'a' && firstLetter <= 'z') {
            firstLetter = (char) (firstLetter - 32);
        }
        chars[0] = firstLetter;
        StringBuilder sb = new StringBuilder();
        for (char c : chars) {
            sb.append(c);
        }
        return sb.toString();
    }

    private static final double SIZE_1K = 1024;
    private static final double SIZE_1M = 1048576;
    private static final double SIZE_1G = 1073741824;

    /**
     * 将文件大小格式化成xxG xxM等格式
     *
     * @param size
     * @return
     */
    public static String formatSize(long size) {
        DecimalFormat df = new DecimalFormat("#.##");
        if (size < SIZE_1K) {
            return String.valueOf(size);
        } else if (size < SIZE_1M) {
            return df.format(size / SIZE_1K).concat("K");
        } else if (size < SIZE_1G) {
            return df.format(size / SIZE_1M).concat("M");
        } else {
            return df.format(size / SIZE_1G).concat("G");
        }
    }

    public static void main(String[] args) {

        String a = "123!456!789";
        String symbol = "!";
        //System.out.println(substringBefore(a, symbol));
        System.out.println(subStringLast(a, symbol));
        //System.out.println(substringAfter(a, symbol));
        String word = "test_cz";
        System.out.println(getCamelCaseField(word));
    }
}
